package com.paho;

import com.paho.properties.PahoProperties;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.nio.charset.StandardCharsets;

/**
 * @Author wdy
 * @Date 2023/9/19
 **/
@RequiredArgsConstructor
@EnableConfigurationProperties(PahoProperties.class)
public class PahoTemplate {

    private final MqttClient mqttClient;
    private final PahoProperties pahoProperties;

    /**
     * 发送消息
     *
     * @param topic   消息主题
     * @param message 消息内容
     * @param qos     消息QOS
     * @param retain  是否保留消息
     */
    public void send(String topic, String message, Integer qos, Boolean retain) {
        try {
            mqttClient.publish(topic, message.getBytes(StandardCharsets.UTF_8), qos, retain);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 发送消息
     *
     * @param topic   消息主题
     * @param message 消息内容
     * @param qos     消息QOS
     */
    public void send(String topic, String message, Integer qos) {
        this.send(topic, message, qos, pahoProperties.getRetain() == 1);
    }

    /**
     * 发送消息
     *
     * @param topic   消息主题
     * @param message 消息内容
     */
    public void send(String topic, String message) {
        this.send(topic, message, pahoProperties.getQos() == null ? 0 : pahoProperties.getQos(), pahoProperties.getRetain() == 1);
    }

}
